package com.xj.demo.unknow;

import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import java.lang.management.MemoryUsage;

public class ManagementFactoryTest {
    public static void main(String[] args) {
        MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
        MemoryUsage heapMemoryUsage = memoryMXBean.getHeapMemoryUsage();
        long init = heapMemoryUsage.getInit();
        long used = heapMemoryUsage.getUsed();
        long max = heapMemoryUsage.getMax();
        System.out.println(String.format("初始堆大小：%sMB；最大堆大小：%sMB；已使用堆大小：%sMB", (init / 1024 / 1024),(max / 1024 / 1024),(used / 1024 / 1024)));
        MemoryUsage nonHeapMemoryUsage = memoryMXBean.getNonHeapMemoryUsage();
        long nonHeapMemoryUsageInit = nonHeapMemoryUsage.getInit();
        long nonHeapMemoryUsageUsed = nonHeapMemoryUsage.getUsed();
        long nonHeapMemoryUsageMax = nonHeapMemoryUsage.getMax();
        long committed = nonHeapMemoryUsage.getCommitted();
        System.out.println(String.format("初始非堆大小：%sMB；最大非堆大小：%sMB；已使用非堆大小：%sMB，已提交大小：%sMB",
                (nonHeapMemoryUsageInit / 1024 / 1024),(nonHeapMemoryUsageMax / 1024 / 1024),(nonHeapMemoryUsageUsed / 1024 / 1024),(committed / 1024 / 1024))
        );
        Runtime runtime = Runtime.getRuntime();
        long totalMemory = runtime.totalMemory();
        long maxMemory = runtime.maxMemory();
        long freeMemory = runtime.freeMemory();
        System.out.println(String.format("当前堆大小：%sMB；最大可用堆内存：%sMB；空闲堆内存：%sMB",
                (totalMemory / 1024 / 1024),(maxMemory / 1024 / 1024),(freeMemory / 1024 / 1024))
        );
    }
}
